import fitz
import os

directory_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
basepath = os.path.join(directory_path, 'file')
graphpath = os.path.join(directory_path, 'graph')

def pdf_to_text(file_path):
    PDFText = {}
    for file in os.listdir(basepath):
        file_path = os.path.join(basepath, file)
        # 检查是否为pdf文件
        if os.path.isfile(file_path) and file_path.endswith('.pdf'):
            filename = file.split('.')[0]
            allText = []
            doc = fitz.open(file_path)

            # 读取PDF文件内容
            for page in doc:
                text = page.get_text("text")
                # print(text)
                textSplit = text.split('\n')
                # print(textSplit)
                allText.extend(textSplit)

            textString = ''.join(allText)
            print(textString)
            print(len(textString))

            PDFText[filename] = textString
    return PDFText

def pdf_to_image(file_path):
    for file in os.listdir(basepath):
        file_path = os.path.join(basepath, file)
        # 检查是否为pdf文件
        if os.path.isfile(file_path) and file_path.endswith('.pdf'):
            filename = file.split('.')[0]
            doc = fitz.open(file_path)
            # 输出最后两页的图片
            new_graph_path = os.path.join(graphpath, filename)
            try:
                # 创建新文件夹
                os.mkdir(new_graph_path)
                print(f"成功在 {graphpath} 下创建文件夹 {filename}")
            except FileExistsError:
                print(f"文件夹 {graphpath} 已存在。")
            except PermissionError:
                print("没有权限创建文件夹。")
            except Exception as e:
                print(f"创建文件夹时出现错误: {e}")

            page_last = doc[-1]
            pix1 = page_last.get_pixmap()
            pix1.save(os.path.join(new_graph_path, 'last_page.png'))

            page_second_last = doc[-2]
            pix2 = page_second_last.get_pixmap()
            pix2.save(os.path.join(new_graph_path, 'second_page.png'))
